package com.twotiger.and.activity.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.R.string;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.animation.Animator.AnimatorListener;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.account.recharge.RechargePage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.project.debt.DebtInverstConfirmPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.Coupon;
import com.twotiger.and.bean.InverstCoupon;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.UserAsset;
import com.twotiger.and.bean.UserBanklist;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.DateUtil;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.ViewUtils;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;

/**
 * 投资确认
 * @Description: TODO(这里描述这个类的作用) 
 * @Author gao
 * @Date 2015年8月12日 下午2:46:16
 */
public class InverstConfirmPage extends BaseActivity {

    private static final int GETCUNBANKSUCCES = 2;
    private static final int GETCUNBANKFAIL = 3;
    private static final int GETINVESTSUCCES = 4;
    private static final int GETINVESTFAIL = 5;
    public static final int COUPONRESULT_CANCELED = 6; //优惠券暂不使用的标记
    private static final int GETASSERTSUCCES = 7;
    private static final int GETASSERTFAIL = 8;
    
    public static final String ZHITOU = "zhitou";

    private TextView sub_title_center_tv;
    private ImageView sub_title_left_bt;
    private TextView project_name;
    private TextView year_interest;
    private TextView repay_type;
    private TextView invest_amount;
    private TextView expect_income;
    private Button confirm_pay;
    private TextView count_time;
    private TextView repay_time;
    private TextView real_amount;
    private TextView tv_coupon_name,tv_coupon_value;
    private HashMap<String, String> parm;
    private Order order;
    private Double couponvalue = 0.00;
    private double reallyamount = 0.00;  //实付金额
    private TextView invest_date;
    private Coupon usedCoupon; //使用的优惠券
    private LinearLayout ll_show_detail;
    private ImageView iv_arrow;

    private boolean isShow;
    private LinearLayout ll_detail;

    @Override
    protected void processLogic() {
        sub_title_left_bt.setVisibility(View.VISIBLE);
        
        parm = getParm();
        order = (Order) getIntent().getExtras().getSerializable("ORDER");
        usedCoupon = (Coupon) getIntent().getExtras().getSerializable("COUPON");
        int num = getIntent().getIntExtra("NUMBER", -1);
        reallyamount = order.getInverstamount();
        
        if(usedCoupon !=null){
            switch (usedCoupon.getAwardType()) {
            case 4:
                //代金券
                tv_coupon_name.setText(usedCoupon.getAwardValue()+"元"+usedCoupon.getAwardTypeName());
                tv_coupon_value.setText("已抵用"+ArithUtils.coverMoney(usedCoupon.getAwardValue()+"")+"元");
                reallyamount = ArithUtils.sub(order.getInverstamount(), usedCoupon.getAwardValue());
                couponvalue = usedCoupon.getAwardValue();
                break;
            case 1:
                //加息券
                tv_coupon_name.setText(usedCoupon.getAwardValue()+"%"+usedCoupon.getAwardTypeName());
                tv_coupon_value.setText("可额外产生"+ArithUtils.coverMoney(usedCoupon.getAddInterest()+"")+"元");
                break;
            default:
                break;
            }
            
        }else {
            if(num == 0){
                tv_coupon_name.setText("暂无可用优惠券");
                tv_coupon_name.setTextColor(getResources().getColor(color.color_gray));
                tv_coupon_value.setText("");
            }else{
                tv_coupon_name.setText("暂不使用优惠券");
                tv_coupon_name.setTextColor(getResources().getColor(color.color_gray));
                tv_coupon_value.setText("");
            }
        }
        sub_title_center_tv.setText("订单确认");
        project_name.setText(order.getProjectname());
        year_interest.setText("" + order.getProject_yield() + "%");
        repay_type.setText("" + order.getRepaymenttype());
        invest_date.setText("" + order.getRecyle() + "天");
        invest_amount.setText("" + ArithUtils.coverMoney(order.getInverstamount() + "") + "元");
        expect_income.setText("" + ArithUtils.coverMoney(order.getExpectinterest() + "") + "");
        count_time.setText("起息时间：" + DateUtil.getlongtoDate(order.getStartyidtime()) + "（明天）");
        repay_time.setText("还款时间：" + DateUtil.getlongtoDate(order.getStartrepytime()));
        real_amount.setText("实付金额：" + ArithUtils.coverMoney(reallyamount + "") + "元");
        
    }

    @Override
    protected void onRestart() {
        getuserassert();
        super.onRestart();
    }

    /**
     * 获取用户资产信息
     */
    private void getuserassert() {
        parm.clear();
        parm.put("token", getToken());
        getDate(parm, Constants.ASSETQUERY, handler, GETASSERTSUCCES, GETASSERTFAIL, true, true,
            false);
    }

    @Override
    protected void setListener() {
        confirm_pay.setOnClickListener(this);
        sub_title_left_bt.setOnClickListener(this);
        ll_show_detail.setOnClickListener(this);
        
        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETASSERTSUCCES: //获取用户资产信息成功
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        UserAsset userAsset = JSONObject.parseObject(result.data, UserAsset.class);
                        order.setCanuse(userAsset.avaliable);
                    } else {
                        showToast(result.codeDesc);
                    }
                    break;


                case GETCUNBANKSUCCES:
                    UserBanklist cunbanklist = JSON.parseObject((String) msg.obj,
                        UserBanklist.class);
                    if (cunbanklist.isOk()) {
                        Intent intent = new Intent(mContext, RechargePage.class);
                        intent.putExtra("CHONGZHI_JSON", (String) msg.obj);
                        intent.putExtra("CHARGE", order.getCanuse());
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    } else {
                        showToast(cunbanklist.codeDesc);
                    }
                    break;
                case GETCUNBANKFAIL:
                case GETINVESTFAIL:
                case GETASSERTFAIL:
                    showToast("网络超时");
                    break;
                case GETINVESTSUCCES:
                    Basebean result_i = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_i.isOk()) {
                        BroswerUrl url = JSON.parseObject(result_i.data, BroswerUrl.class);
                        Intent intent = new Intent(mContext, WebViewPage.class);
                        intent.putExtra("url", url.getUrl());
                        intent.putExtra("title", "投资");
                        intent.putExtra("SHOWPASSWORD", "showPassword");
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_INVESTTENDER);
                        startNewActivityforresult(intent, R.anim.push_left_in,
                            R.anim.push_left_out, ProjectDetailPage.TENDERREQUEST);
                    } else {
                        showToast(result_i.codeDesc);
                    }
                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
    }

    @Override
    protected void findViewById(View view) {
        sub_title_center_tv = (TextView) view.findViewById(R.id.sub_title_center_tv);
        sub_title_left_bt = (ImageView) view.findViewById(R.id.sub_title_left_bt);
        project_name = (TextView) view.findViewById(R.id.project_name);
        tv_coupon_name = (TextView) view.findViewById(R.id.tv_coupon_name);
        tv_coupon_value = (TextView) view.findViewById(R.id.tv_coupon_value);
        year_interest = (TextView) view.findViewById(R.id.year_interest);
        repay_type = (TextView) view.findViewById(R.id.repay_type);
        invest_amount = (TextView) view.findViewById(R.id.invest_amount);
        expect_income = (TextView) view.findViewById(R.id.expect_income);
        count_time = (TextView) view.findViewById(R.id.count_time);
        repay_time = (TextView) view.findViewById(R.id.repay_time);
        real_amount = (TextView) view.findViewById(R.id.real_amount);
        confirm_pay = (Button) view.findViewById(R.id.confirm_pay);
        invest_date = (TextView) view.findViewById(R.id.invest_date);

        ll_detail = (LinearLayout) view.findViewById(R.id.ll_detail);
        ll_show_detail = (LinearLayout) view.findViewById(R.id.ll_show_detail);
        iv_arrow = (ImageView) view.findViewById(R.id.iv_arrow);
        
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }


    //提交投资订单
    private void inverst_order() {
        parm.clear();
        parm.put("token", getToken());
        parm.put("projectId", order.getProjectid());
        parm.put("amount", ArithUtils.coverMoney(order.getInverstamount() + ""));
        if (usedCoupon != null) {
            parm.put("caId", usedCoupon.getCaId());
        }
        parm.put("type", order.getType());
        parm.put("mode", order.getMode());
        getDate(parm, Constants.INVEST, handler, GETINVESTSUCCES, GETINVESTFAIL, true, true,
            false);
    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.order_confirmation_layout, null);
        return view;
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        if (requestcode == ProjectDetailPage.TENDERREQUEST) {
            if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_SUC) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_SUC);
                finish();
            } else if (resultcode == ProjectDetailPage.TENDERRESULTCLOSE_FAI) {
                setResult(ProjectDetailPage.TENDERRESULTCLOSE_FAI);
                finish();
            }
        }

        super.onActivityResult(requestcode, resultcode, intent);
    }
    
    /**
     * 让view做一个动画来显示出来
     */
    private void doViewAnimation(boolean boo) {

        ValueAnimator valueAnimator = null;
        if (boo) {
            valueAnimator = ValueAnimator.ofInt(0, ViewUtils.dip2px(InverstConfirmPage.this, 100));
        } else {
            valueAnimator = ValueAnimator.ofInt(ViewUtils.dip2px(InverstConfirmPage.this, 100), 0);
        }
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                int value = (Integer) animator.getAnimatedValue();
                //获取动画的值，设置给acount_grid的高度
                LogUtil.info("totalHeight:" + "value " + value);
                ll_detail.getLayoutParams().height = value;
                //acount_grid.setLayoutParams(acount_grid.getLayoutParams());
                ll_detail.requestLayout();
            }
        });
        valueAnimator.setDuration(500);
        valueAnimator.addListener(new AnimatorListener() {
            @Override
            public void onAnimationStart(Animator arg0) {
                if(!isShow){
                    ViewPropertyAnimator.animate(iv_arrow).rotationBy(180).setDuration(50);
                }else {
                    ViewPropertyAnimator.animate(iv_arrow).rotationBy(-180).setDuration(50);
                }
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                isShow = !isShow;
            }

            @Override
            public void onAnimationCancel(Animator arg0) {

            }
        });
        valueAnimator.start();
    }

    @Override
    public void onClick(View view) {
        final Intent intent = new Intent();
        switch (view.getId()) {
        case R.id.ll_show_detail:
            doViewAnimation(!isShow);
            break;
        case R.id.sub_title_left_bt:
            onBackPress();
            return;
        case R.id.confirm_pay:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (order.getInverstamount() > ArithUtils.add(order.getCanuse(), couponvalue)) {
                PromptManager.showConfirmAlert2(mContext,
                    0, "账户余额不足", "我们先来充个值吧", "取消", "充值", true,
                    new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {
                            
                        }

                        @Override
                        public void onClickCancel() {
                            intent.setClass(mContext, RechargePage.class);
                            intent.putExtra("SCENE", RechargePage.SCENE_ORDER);
                            intent.putExtra("ORDER", order);
                            intent.putExtra("COUPON", usedCoupon);
                            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out,
                                false);
                        }
                    });
                return;
            }
            inverst_order();
            break;
        default:
            break;
        }
    }
}
